package logic

import (
	"context"
	"fmt"
	"math/rand"
	"time"
	"zhihu/zhihurpc/models/redis"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *zhihurpc.SendSmsRequest) (*zhihurpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := redis.Rdb.Get(l.ctx, "sendnumber"+in.Mobile).Result()
	if result >= "1" {
		return nil, fmt.Errorf("短信一分钟内已发过一次,请稍后再试")
	}
	code := rand.Intn(9000) + 1000
	redis.Rdb.Set(l.ctx, "sendSms"+in.Mobile, code, time.Minute*3)
	redis.Rdb.Set(l.ctx, "sendnumber"+in.Mobile, 1, time.Minute*1)
	redis.Rdb.Expire(l.ctx, "sendnumber"+in.Mobile, time.Minute*1)
	return &zhihurpc.SendSmsResponse{}, nil
}
